#
#  QGpgAppDelegate.py
#  QGpg
#
#  Created by Paul on 1/15/08.
#  Copyright __MyCompanyName__ 2008. All rights reserved.
#

from Foundation import *
from AppKit import *
from GPGUtils import GPGHelper
from Growl import *
import objc

class QGpgAppDelegate(NSObject):
    
    statusMenu = objc.IBOutlet()
    passDialog = objc.IBOutlet()
    passFileDialog = objc.IBOutlet()
    passEncryptDialog = objc.IBOutlet()
    passEncryptFileDialog = objc.IBOutlet()
    decryptDialog = objc.IBOutlet()
    decryptFileDialog = objc.IBOutlet()

    addressToken = objc.IBOutlet()
    passPhrase = objc.ivar(u"passPhrase")
    addressList = objc.ivar(u"addressList")

    def applicationDidFinishLaunching_(self, sender):
        NSLog("Stopped fuckin...")
        # Setup statusbar:
        statusbar = NSStatusBar.systemStatusBar()
        self.statusbarIcon = statusbar.statusItemWithLength_(NSVariableStatusItemLength)
        statusIcon = NSImage.alloc().initByReferencingFile_(NSBundle.mainBundle().resourcePath() + '/Lock.pdf')
        self.statusbarIcon.setImage_(statusIcon)
        self.statusbarIcon.setHighlightMode_(1)
        self.statusbarIcon.setToolTip_('This is QGpg. Hello.')
        self.statusbarIcon.setMenu_(self.statusMenu)
        try :
            self.__growl__ = GrowlNotifier(applicationName="qgpg",
                                           notifications=["qgpg"],
                                           defaultNotifications=["qgpg"])
        except Exception, e :
           NSLog("Failed to create notification agent, %s", e)
        try :
           self.__growl__.register()
        except Exception, e :
           NSLog("Failed to register notification agent, %s", e)

    def setPassPhrase_(self, value):
        self.passPhrase = value

    def decodeText(self):
        plaintext = self.getClipboard()
        if plaintext and plaintext.startswith("-----BEGIN PGP MESSAGE-----"):
            gpgHelper = GPGHelper(self.passPhrase)
            plaintext = gpgHelper.decryptMessage(plaintext)
            if plaintext:
                self.setClipboard(plaintext)
                self.growl("Decrypted", gpgHelper.message)
            else:
                self.growl("Decryption Failed", gpgHelper.message)
        else:
            self.growl("Decryption Failed", "Clipboard does not contain encrypted text")

    def encodeSignFile(self):
        panel = NSOpenPanel.openPanel()
        rval = panel.runModalForTypes_(None)
        if rval == NSOKButton:
            gpgHelper = GPGHelper(self.passPhrase)
            self.passPhrase = None
            if gpgHelper.encryptSignFile(panel.filenames()[0], self.addressList):
                self.growl("Encrypted", "The encrypted file is in the same folder as the original file")
            else:
                self.growl("Encryption failed", gpgHelper.message)

    def encodeSignText(self):
        plaintext = self.getClipboard()
        gpgHelper = GPGHelper(self.passPhrase)
        self.passPhrase = None
        if gpgHelper.encryptSignMessage(plaintext, self.addressList):
            self.setClipboard(gpgHelper.message)        
            self.__growl__.notify("qgpg", "Encrypted", "You can now paste the signed messager", None, False)
        else:
            self.__growl__.notify("qgpg", "Encryption failed", gpgHelper.message, None, False)

    @objc.IBAction
    def exportKey_(self, sender):
        gpgHelper = GPGHelper("")
        if gpgHelper.exportingKey():
            self.setClipboard(gpgHelper.message)        
            self.__growl__.notify("qgpg", "Exported", "You can now paste your public key(s)", None, False)
        else:
            self.__growl__.notify("qgpg", "Export failed", gpgHelper.message, None, False)

    def decodeFile(self):
        panel = NSOpenPanel.openPanel()
        rval = panel.runModalForTypes_(['gpg', 'pgp', 'asc', 'sig'])
        if rval == NSOKButton:
            gpgHelper = GPGHelper(self.passPhrase)
            self.passPhrase = None
            if gpgHelper.decryptFile(panel.filenames()[0]):
                self.growl("Decoded", "The decoded file is in the same folder as the original file.\n\n" + gpgHelper.message)
            else:
                self.growl("Decode failed", gpgHelper.message)

    @objc.IBAction
    def verifyFile_(self, sender):
        panel = NSOpenPanel.openPanel()
        rval = panel.runModalForTypes_(['gpg', 'pgp', 'asc'])
        if rval == NSOKButton:
            gpgHelper = GPGHelper(None)
            if gpgHelper.verifyFile(panel.filenames()[0]):
                self.__growl__.notify("qgpg", "Verification", gpgHelper.message, None, True)
            else:
                self.__growl__.notify("qgpg", "Verification Failed", gpgHelper.message, None, True)

    def signFile(self):
        panel = NSOpenPanel.openPanel()
        rval = panel.runModalForTypes_(None)
        if rval == NSOKButton:
            gpgHelper = GPGHelper(self.passPhrase)
            self.passPhrase = None
            if gpgHelper.signFile(panel.filenames()[0]):
                self.growl("Signed", "The signature file is in the same folder as the original file")
            else:
                self.growl("Signing failed", gpgHelper.message)

    def signText(self):
        plaintext = self.getClipboard()
        gpgHelper = GPGHelper(self.passPhrase)
        self.passPhrase = None
        if gpgHelper.signMessage(plaintext):
            self.setClipboard(gpgHelper.message)        
            self.__growl__.notify("qgpg", "Signed", "You can now paste the signed message", None, False)
        else:
            self.__growl__.notify("qgpg", "Signing failed", gpgHelper.message, None, False)

    @objc.IBAction
    def verifyText_(self, sender):
        plaintext = self.getClipboard()
        gpgHelper = GPGHelper("")
        if gpgHelper.verifyMessage(plaintext):
            self.__growl__.notify("qgpg", "Verification", gpgHelper.message, None, True)
        else:
            self.__growl__.notify("qgpg", "Verification Failed", gpgHelper.message, None, True)
        
    def getClipboard(self):
        return NSPasteboard.generalPasteboard().stringForType_(NSStringPboardType)
    def setClipboard(self, plaintext):
        NSPasteboard.generalPasteboard().declareTypes_owner_([NSStringPboardType], None)
        NSPasteboard.generalPasteboard().setString_forType_(plaintext, NSStringPboardType)

    @objc.IBAction
    def passContinue_(self, sender):
        if sender.tag() == 1:
            if self.passPhrase:
                self.passDialog.orderOut_(None)
                self.signText()
        elif sender.tag() == 2:
            if self.passPhrase and self.addressList:
                self.passEncryptDialog.orderOut_(None)
                self.encodeSignText()
        elif sender.tag() == 3:
            if self.passPhrase and self.addressList:
                self.passEncryptFileDialog.orderOut_(None)
                self.encodeSignFile()
        elif sender.tag() == 4:
            if self.passPhrase:
                self.decryptDialog.orderOut_(None)
                self.decodeText()
        elif sender.tag() == 5:
            if self.passPhrase:
                self.passFileDialog.orderOut_(None)
                self.signFile()
        elif sender.tag() == 6:
            if self.passPhrase:
                self.decryptFileDialog.orderOut_(None)
                self.decodeFile()


    @objc.IBAction
    def passCancel_(self, sender):
        self.passPhrase = None
        if sender.tag() == 1:
            self.passDialog.orderOut_(None)
        elif sender.tag() == 2:
            self.passEncryptDialog.orderOut_(None)
        elif sender.tag() == 3:
            self.passEncryptFileDialog.orderOut_(None)
        elif sender.tag() == 4:
            self.decryptDialog.orderOut_(None)
        elif sender.tag() == 5:
            self.passFileDialog.orderOut_(None)
        elif sender.tag() == 6:
            self.decryptFileDialog.orderOut_(None)

    def growl(self, title, message):
        self.__growl__.notify("qgpg", title, message, None, True)